package com.yyh.synctool.client.test;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //根据名字获取工厂中指定的Bean对象
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    // 通过类型获取上下文中的bean
    public static Object getBean(Class<?> requiredType) {
        return context.getBean(requiredType);
    }

    public void registryNewBean() {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();

        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(SqlSessionFactory.class);
        //genericBeanDefinitio
        registry.registerBeanDefinition("taskMapper", genericBeanDefinition);
    }

    public void removeExistingAndAddNewBean(String beanId) {

        AutowireCapableBeanFactory factory =
                context.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
        registry.removeBeanDefinition(beanId);

        //create newBeanObj through GenericBeanDefinition

        //registry.registerBeanDefinition(beanId, newBeanObj);
    }
}
